package com.eff.android.fragment.main.start;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.eff.android.R;
import com.eff.android.api.model.Model;
import com.eff.android.api.model.Setting;
import com.eff.android.config.EConstant;
import com.eff.android.fragment.EBaseFragment;
import com.eff.android.fragment.IFragmentCallback;
import com.eff.android.lib.graphics.Base64Convert;
import com.eff.android.lib.helper.EDatabaseHelper;
import com.eff.android.lib.helper.EHelpMenu;
import com.eff.android.lib.helper.EStringHelper;
import com.eff.android.lib.ui.ActionBarController;
import com.eff.android.lib.ui.EImageView;
import com.eff.android.lib.ui.ERowView;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

public class EMainFragmentPronounciation extends EBaseFragment {

	public static final String TAG = EMainFragmentPronounciation.class.getSimpleName();
	
	public EMainFragmentPronounciation(Bundle arguments) {
		super(arguments);
	}

    private EStringHelper stringHelper;
    
    private List<Model> models;
    private int sizeShowModel = EConstant.NUMBER_OF_IMAGE;
    
    private Button btnRec;    
    //private Setting settings;
    private List<ERowView> listRowView;
    Animation animate = null;
    
    private IFragmentCallback callback;

    //Danh sach tu da doc dung, 1: da doc dung, 0: chua doc
	private int[] m_currectList = null;
	int numberOfFalseWord = 0;

	public static Bundle getArgs() {
		Bundle b = new Bundle();
		b.putString(TAG, TAG);
		return b;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Init();
	}
	
	public void Init (){
		Log.d("sizeShowModel", String.valueOf(sizeShowModel));
		Log.d("SubjectID", Setting.newInstance().getSubject().getSubjectID());
		Log.d("SubjectName", Setting.newInstance().getSubject().getSubjectName());
		Log.d("Type", Setting.newInstance().getType().name());
		Log.d("Level", Setting.newInstance().getLevel().name());
		
		models = EDatabaseHelper.getInstance(getActivity().getApplicationContext())
				.getAllModels(sizeShowModel, Setting.newInstance().getSubject(), 
						Setting.newInstance().getType(), Setting.newInstance().getLevel());
		
		if (models.size() < sizeShowModel) {					
			android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);	
		}
		
		initFragments();
		initCheckList();
		getActivity().getActionBar().show();		
		animate = AnimationUtils.loadAnimation(getActivity(), R.anim.scaleanimate);
		stringHelper = new EStringHelper();
	}
	
	private void initCheckList(){
		m_currectList = new int[10];
		for(int i=0; i<10; i++)
			m_currectList[i] = 0;	
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		
		configActionBar(inflater);
		
		View v = inflater.inflate(R.layout.e_frm_main_start_pronunciation, container, false);
		initViews(v);
		
		return v;
    }
	
	private void configActionBar(LayoutInflater inflater) {
		
		View mCustomView = inflater.inflate(R.layout.e_actionbar_default, null);
		btnRec = (Button)mCustomView.findViewById(R.id.btnRec);
		btnRec.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// Record Process
				promptSpeechInput();
			}
		});
		
		ActionBarController.getInstance().SetActionBarCustomView(getActivity().getActionBar(), mCustomView);
    }
	
	private void initViews(View v) {
		
		listRowView = new ArrayList<ERowView>();
		initRowItems(v);
		LinearLayout layout = (LinearLayout)v.findViewById(R.id.imageViewLayout);
		for(int i=0; i<listRowView.size(); i++){
			layout.addView(listRowView.get(i));
			ProcessClickedEvent(i);			
		}
	}
	
	private void initRowItems(View v){
		Base64Convert convertor = new Base64Convert();
		
        for (int i = 0; i < sizeShowModel; i=i+2) {
        	//Create Bitmap
        	Bitmap iconLeft = convertor.Decompress(models.get(i).getUriHinh(), Base64.DEFAULT);
        	Bitmap iconRight = convertor.Decompress(models.get(i+1).getUriHinh(), Base64.DEFAULT);
        	
        	EImageView left = new EImageView(v.getContext(), models.get(i).getVanBan(), iconLeft);
        	EImageView right = new EImageView(v.getContext(), models.get(i+1).getVanBan(), iconRight);
        	ERowView rowView = new ERowView(v.getContext(), left, right);
        	listRowView.add(rowView);      	
        }
	}
	
	private void ProcessClickedEvent(int i){
		TextClickedEventProcessor(i);
		ImageClickedEventProcessor(i);
	}
	
	private void TextClickedEventProcessor(int i){
		final int k = 2*i;
		// Click on Text
		listRowView.get(i).getImageViewLeft().getWordText().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ShowMenuHelper(v, k);
			}
		});
						
		listRowView.get(i).getImageViewRight().getWordText().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ShowMenuHelper(v, k+1);
			}
		});
	}
	
	private void ImageClickedEventProcessor(int i){
		final int k = 2*i;
		// Click on Image
		listRowView.get(i).getImageViewLeft().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ShowMenuHelper(v, k);
			}
		});
							
		listRowView.get(i).getImageViewRight().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ShowMenuHelper(v, k+1);
			}
		});
	}
	//Display menu helper
	public void ShowMenuHelper(View view, int id) {
		EHelpMenu helpMenu;
		helpMenu = new EHelpMenu(view, models.get(id));
		helpMenu.Show();
		helpMenu.ProcessClickEvent(getActivity());
	}
	
	/**
	 * Showing google speech input dialog
	 * */
	private void promptSpeechInput() {
		
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.US);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
				getString(R.string.speech_prompt));
		try {
			startActivityForResult(intent, EConstant.REQ_CODE_SPEECH_INPUT);			
		} catch (ActivityNotFoundException a) {
			Toast.makeText(getActivity().getApplicationContext(),
					getString(R.string.speech_not_supported),
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Receiving speech input
	 * */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		switch (requestCode) {
			case EConstant.REQ_CODE_SPEECH_INPUT: {
				if (resultCode == getActivity().RESULT_OK && null != data) {
					ArrayList<String> results = data
							.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
					String txtSpeechInput = results.get(0);					
					txtSpeechInput = stringHelper.normalizeFormat(txtSpeechInput);
					// Show Speech to text
					Toast.makeText(getActivity().getApplicationContext(),
							txtSpeechInput, Toast.LENGTH_SHORT);
					
					int result = CompareString(txtSpeechInput);					
					NotifyResult(result);
						
				}
				break;
			}	

		}
	}
	
	private int CompareString(String txtSpeechInput) {
		for (int i = 0; i < models.size(); i++) {
			
			String compare = models.get(i).getVanBan().toString();					
			compare = stringHelper.normalizeFormat(compare);
			
			// process true or false						
			if (txtSpeechInput.compareTo(compare) == 0)
			{	
				/*Kiem tra tu da duoc doc chua*/
				if(m_currectList[i] == 1)
					return -1;			
				// location correct in models => flag != -1
				return i;
			}					
		}
		
		return -1;
	}
	
	private void NotifyResult(int result){
		// not found
		if (result == -1) {
			Toast.makeText(getActivity().getApplicationContext(),
					"InCorrect!!!", Toast.LENGTH_SHORT).show();
		}
		else {
			// found it						
			Toast.makeText(getActivity().getApplicationContext(),
					"Correct!!!", Toast.LENGTH_SHORT).show();	
			updateListModel(result);
		}
	}

	/**Update check list
	*Cac tu doc dung se duoc gan gia tri la 1
	*va se khong kiem tra nua
	*/
	private void updateListModel(int locationRemove) {
		m_currectList[locationRemove] = 1;		
		RefreshListView(locationRemove);
	}
	
	private void initFragments() {
		//eMainFragmentRecord = EMainFragmentStartRecord.newInstance(this.getArguments());
	}	
	
	/**
	 * Tinh toan lai hieu ung va cap nhat lai hinh anh
	 * @param index
	 * 	vi tri cua tu trong listmodel
	 *  Tat ca chia cho 2
	 *  	Phan nguyen: row id
	 *  	Phan du: 0: left 1: right
	 */
	private void RefreshListView(int index){
		
		//if index = -1 : End function
		if(index == -1)
			return;

		//Log.i("Recode", String.valueOf(index));
		int iRow = index / 2;
		EImageView selected = null;
		
		switch(index % 2)
		{
		case 0:
			selected = this.listRowView.get(iRow).getImageViewLeft();
			selected.startAnimation(animate);
			selected.setVisibility(View.GONE);
			break;
		case 1:
			selected = this.listRowView.get(iRow).getImageViewRight();
			selected.startAnimation(animate);
			selected.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}
	
	public IFragmentCallback getCallback() {
		return callback;
	}

	public void setCallback(IFragmentCallback callback) {
		this.callback = callback;
	}
	
}
